package com.wangjie.minio.policy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class MinioPolicyLoader {
    private static final Logger logger = LoggerFactory.getLogger(MinioPolicyLoader.class);

    private static final String[] POLICY_LOCATIONS = {"classpath:minio/minio-policy.json", "classpath:minio-policy.json"};

    private final ResourceLoader resourceLoader;

    public MinioPolicyLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public String loadPolicy(String bucketName) {
        for (String location : POLICY_LOCATIONS) {
            Resource resource = resourceLoader.getResource(location);
            if (!resource.exists()) {
                continue;
            }
            try {
                String policy = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
                return policy.replace("${bucketName}", bucketName);
            } catch (IOException e) {
                logger.error("Error loading policy from resource: {}", e.getMessage());
                return null;
            }
        }
        logger.info("Using default bucket policy");
        return createDefaultPolicy(bucketName);
    }

    private String createDefaultPolicy(String bucketName) {
        StringBuffer sb = new StringBuffer();
        sb.append("{")
                .append("    \"Version\": \"2012-10-17\",")
                .append("    \"Statement\": [")
                .append("        {")
                .append("            \"Effect\": \"Allow\",")
                .append("            \"Principal\": \"*\",")
                .append("            \"Action\": [")
                .append("                \"s3:GetObject\"")
                .append("            ],")
                .append("            \"Resource\": [")
                .append("                \"arn:aws:s3:::" + bucketName + "/*\"")
                .append("            ]")
                .append("        }")
                .append("    ]")
                .append("}");
        return sb.toString();
    }
}
